package cn.example.vip.mall.order.rocketmq;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.List;

@RocketMQMessageListener(topic = "log", consumerGroup = "result-group")
@Component
public class OrderResultListener implements RocketMQListener, RocketMQPushConsumerLifecycleListener {
	@Override
	public void onMessage(Object o) {
	
	}
	
	/**
	 * 消息监听
	 * @param defaultMQPushConsumer
	 */
	@Override
	public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {
		defaultMQPushConsumer.registerMessageListener(new MessageListenerConcurrently(){
			@Override
			public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
				try {
					for (MessageExt messageExt : list) {
						String result = new String(messageExt.getBody(), StandardCharsets.UTF_8);
						System.out.println(result);
					}
				}catch (Exception e){
					e.printStackTrace();
					// 异常 回滚事务
					return ConsumeConcurrentlyStatus.RECONSUME_LATER;
				}
				return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
			}
		});
	}
}
